﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using eLearning.Models;
using eLearning.Business;
using eLearning.Helpers;
using eLearning.ViewModels;
using System.Web.Mvc;
using System.Data;

namespace eLearning.Repository
{
    public class SettingManagementRepository : BaseManagementRepository
    {
        // Create an instance of entities framework
        Lead2012Entities entities = new Lead2012Entities();

        public void GetModel(SettingViewModel model)
        {
            FieldManagementRepository repository = new FieldManagementRepository();
            // Set value
            model.ListFields = repository.GetFieldGroup();
            model.FieldSystemList = GetAllFieldSystem();
        }

        #region Public methods
        public void UpdateSettings(List<FieldSystemItem> list)
        {
            // add field system mapped
            FieldSystemRepository repository = new FieldSystemRepository();
            if (list != null && list.Count > 0 && list.Count == 5)
            {
                // Delete all fieldsystem
                string sql = "Delete [FieldSystem]";
                int value = SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringProfile, CommandType.Text, sql);

                foreach (FieldSystemItem item in list)
                {
                    FieldSystem model = new FieldSystem();
                    model.FieldId = item.FieldId;
                    model.TextColumnName = item.TextColumnName;
                    model.ValueColumnName = string.Format("f{0}", item.FieldId);
                    model.Tag = item.Tag;
                    model.OrderId = item.OrderId;

                    repository.Create(model);
                }
            }
        }

        #endregion

        #region Private methods
        private List<FieldSystemItem> GetAllFieldSystem()
        {
            List<FieldSystemItem> list = new List<FieldSystemItem>();
            var items = new FieldSystemRepository().GetAll();

            foreach (var item in items)
            {
                FieldSystemItem model = new FieldSystemItem();
                model.FieldId = item.FieldId;
                model.TextColumnName = item.TextColumnName;
                model.ValueColumnName = item.ValueColumnName;
                model.Tag = item.Tag;
                model.OrderId = item.OrderId;
                list.Add(model);
            }

            return list;
        }
        #endregion
    }
}